package com.example.ziputil.service;

import com.example.ziputil.utils.FileUtil;
import com.example.ziputil.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

@Slf4j
@Service
public class ZipUtilService {

    @Value("${fileUpload.config.zip-path}")
    private String DOWNLOAD_ZIP;

    /**
     * 生成传的目录结构的文件夹
     * @param srcNameList 各个目录的集合
     * @param request
     * @param response
     * @throws Exception
     */
    public void zipFile(List<String> srcNameList, HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream out = response.getOutputStream();
        // 压缩文件路径：文件所在路径
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);

            // 1. 生成临时目录
            for (int i = 0; i < srcNameList.size(); i++) {
                File file = new File(DOWNLOAD_ZIP + srcNameList.get(i));
                if (!file.exists()) {
                    file.mkdirs();
                }
//                String taskStr = srcIdList.get(i).substring(srcIdList.get(i).lastIndexOf("/") + 1);
//                List<Map<String, Object>> companyMapList = autoPublishMapper.queryCompanyByTaskId(taskStr);
//                if (companyMapList.size() > 0) {
//                    for (int j = 0; j < companyMapList.size(); j++) {
                        // 要压缩的文件所在的位置，这个得你自己找吧
                        String filePath = "D:\\WorkSpace\\ronghe-文件\\02. 需求、库表\\05. 报送系统\\北京分中心001\\001-001.xlsx";
                        File sourceFile = new File(filePath);
                        FileUtil.copyFile(sourceFile, DOWNLOAD_ZIP + srcNameList.get(i));
//                    }
//                }
            }

            // 2. 判断临时文件是否生成
            File baseFile = new File(DOWNLOAD_ZIP);
            if (!baseFile.exists()) {
                System.out.println("目录不存在");
                return;
            }

            // 3. 生成压缩包
            ZipUtil.zip(DOWNLOAD_ZIP, response);

            // 4. 删除临时目录
            FileUtil.deleteDir(baseFile);

            long end = System.currentTimeMillis();
            log.info("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            log.error("文件压缩失败：" + e.getMessage());
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
